package com.wang.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mall.bean.UmsMember;
import com.wang.mall.feign.JwtToken;
import com.wang.mall.feign.OauthServerFeign;
import com.wang.mall.mapper.UmsMemberMapper;
import com.wang.mall.model.LoginResult;
import com.wang.mall.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements UmsMemberService {

    @Autowired
    private OauthServerFeign oauthServerFeign;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${basic.token:Basic bWFsbC1hcGk6bWFsbC1zZWNyZXQ=}")
    private String basicToken;

    @Override
    public LoginResult login(String username, String password) {

        LoginResult loginResult = new LoginResult();

        ResponseEntity<JwtToken> responseEntity = null;
        try {
            responseEntity = oauthServerFeign.oauth("password", username, password, "member_type", basicToken);
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }

        // 判断是否登陆成功
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new ApiException(ApiErrorCode.FAILED);
        }

        JwtToken jwtToken = responseEntity.getBody();

        // 设置token
        String accessToken = jwtToken.getAccessToken();
        loginResult.setToken(accessToken);


        Jwt jwt = JwtHelper.decode(accessToken);
        String jwtClaims = jwt.getClaims();
        JSONObject jsonObject = JSON.parseObject(jwtClaims);


        UmsMember umsMember = getOne(new LambdaQueryWrapper<UmsMember>().eq(UmsMember::getUsername, username));
        loginResult.setUmsMember(umsMember);

        // 给redis保存一份数据
        // 过期时间
        redisTemplate.opsForValue().set(accessToken, jsonObject.getString("user_name"), 7 * 24 * 3600, TimeUnit.SECONDS);


        return loginResult;
    }
}
